from django.db import models
import datetime

# Create your models here.


class Book(models.Model):
    id = models.AutoField(primary_key=True, auto_created=True)
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish_date = models.DateField(auto_now_add=True)

    # 一对多
    publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE)
    # 多对多
    authors = models.ManyToManyField(to='Author')

    def __str__(self):
        return self.title

    def author_name(self):
        return ','.join([author.name for author in self.authors.all()])

    def to_dict(self):
        resp_dic = {
            'id': self.id,
            'title': self.title,
            'price': self.price,
            'publish_date': self.publish_date,
            'authors': self.author_name()
        }
        return resp_dic


class Publish(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    email = models.EmailField()  # 还是varchar(254) 该字段不是给models看的，而是给后米哦按学到的校验性组件看的


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()

    author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)


class AuthorDetail(models.Model):
    phone = models.BigIntegerField()
    addr = models.CharField(max_length=64)